/*
 * 解析xml
 */
package util;


import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class MyXmlUtil {
	// step 1:DOM解析器的工厂实例
	private DocumentBuilderFactory domFactory = null;
	// step 2:获得具体的dom解析器
	private DocumentBuilder domBuilder = null;
	// step 3:Document对象（根结点）
	private Document document = null;
	//
	NodeList list = null;
	
	public MyXmlUtil(String filePath) throws Exception {
		domFactory = DocumentBuilderFactory.newInstance();;//实例化dom解析器工厂
		domBuilder = domFactory.newDocumentBuilder();//获得具体的dom解析器
		document = domBuilder.parse(filePath);
	}
	
	/*适全三层树（含父亲节点）,只有一个值*/
	public String getConfigure(String node,String name) {
		
		list = document.getElementsByTagName(node);
		
		
		Element element = (Element)list.item(0);
			
		return element.getElementsByTagName(name).item(0).getFirstChild().getNodeValue();
			
	}
	
	public List<String> getValues(String name) {
		list = document.getElementsByTagName(name);
		List<String>valueList =new ArrayList<String>();
		for(int i= 0;i<list.getLength();i++) {
			valueList.add(list.item(i).getFirstChild().getNodeValue());
		}
		return valueList;
	}
	
	//test
	public static void main(String args[]) {
		try {
			MyXmlUtil xml = new MyXmlUtil("seeds.xml");
		
			List<String> sites = xml.getValues("site");
			for(String s:sites) {
				System.out.println(s);
			}
			
			MyXmlUtil configure = new MyXmlUtil("configure.xml");
			String threadNum = configure.getConfigure("thread", "num");
			System.out.println("thread number: "+threadNum);
			String usebloom = configure.getConfigure("bloomFilter", "use");
			System.out.println("bloomFilter: "+usebloom);
			String useRedis = configure.getConfigure("redis", "use");
			System.out.println("useRedis: "+useRedis);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
